﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Windows;
using Microsoft.Xna.Framework.Audio;

namespace ThreeDWorld
{
    public class ContentManager
    {
        public ContentManager(Game game)
        {
            Assets = new Dictionary<string, object>();
            Game = game;
            Root = "/ContentBuild;component/Content/";
            AssetName = "";
        }

        private Dictionary<string, object> Assets
        {
            get;
            set;
        }

        public Game Game
        {
            get;
            private set;
        }

        public string Root
        {
            get;
            set;
        }

        public string AssetName
        {
            get;
            private set;
        }

        public void Unload()
        {
            foreach (object asset in Assets.Values)
            {
                if (asset is IDisposable)
                {
                    (asset as IDisposable).Dispose();
                }
            }
            Assets.Clear();
        }

        public void Unload(string assetName)
        {
            object asset = Assets[assetName];

            if (asset is IDisposable)
            {
                (asset as IDisposable).Dispose();
            }
            Assets.Remove(assetName);
        }

        public T Load<T>(string assetName)
        {
            if (!Assets.ContainsKey(assetName))
            {
                ContentReader reader = null;

                AssetName = assetName;
                try
                {
                    reader = new ContentReader(this, Application.GetResourceStream(new Uri(Root + assetName + ".asset", UriKind.RelativeOrAbsolute)).Stream);
                    Assets.Add(assetName, reader.ReadObject<T>());
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
            return (T)(object)Assets[assetName];
        }
    }
}
